import React, { useEffect, useRef, useState, useMemo } from 'react';
import { SchemaManage } from '@/components/SchemaComponent';
import { connect, history } from 'umi';
import { AssetListManageAPI } from '../common/type';
import { getTableColumns } from '../mconfig';
import { assetListManageServices, calculationService } from '../services';
import { useDataSourceTable } from '../mconfig/useDataSourceTable';
import { getKeyRouter } from '@/utils';
import { message } from 'antd';
import moment from 'moment';
import { GatherModal } from './GatherModal';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';

const AssetListTableManageView: React.FC<AssetListManageAPI.IMaterialManageView> = ({ curRes }) => {
  /** 管理页的ref */
  const MaterialManageViewRef: any = useRef();

  /** 保存表格展开行的key值 */
  const [tableExpantKeys, setTableExpantKeys] = useState<string[]>([]);

  /** 保存展示的表格数据 */
  const [dataSourceTable, setDataSourceTable] = useState<Record<string, any>[]>([]);

  /** 表格选中行的key */
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  /** 表格选中行内容 */
  const [selectedRows, setSelectedRows] = useState<Record<string, any>[]>([]);

  /** 是否展示汇总弹窗 */
  const [isShowGatherModal, setIsShowGatherModal] = useState<Boolean>(false);

  /** 是否展示确认折旧计算弹窗 */
  const [isShowDepreModal, setIsShowDepreModal] = useState<Boolean>(false);

  /**管理页services*/
  const { getManageDataFun, assetListData, loading, pagination, searchList, otherParams } = assetListManageServices(curRes);

  /** 处理是否有子资产 */
  const { onExpandTable, childLoading } = useDataSourceTable(assetListData?.rows, dataSourceTable, setDataSourceTable, tableExpantKeys, setTableExpantKeys);

  /** 切换头部方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    getManageDataFun({ ...params, ...searchValues });
  };

  /** 重置方法 */
  const onReset = (otherParams: AssetListManageAPI.IAssetTableRequestType) => {
    MaterialManageViewRef?.current?.setSearch({
      depreciationDate: moment()?.subtract(1, 'months'),
    });
  };

  /** 搜索方法 */
  const onSearch = (otherParams: AssetListManageAPI.IAssetTableRequestType) => {
    getManageDataFun({ ...otherParams });
  };

  /** 分页方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getManageDataFun({ pageSize, current, ...params });
  };

  /** Table操作列的事件池 */
  const operateFnc: AssetListManageAPI.IMaterialTableActionType = {
    /** 详情资产按钮 */
    onView: (record: Record<string, any>) => {
      history.push({
        pathname: `/assetInfo/resultant/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'detail',
          id: record.id,
        },
      });
    },
  };

  /** Table的columns集合 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, operateFnc);
  }, [curRes]);

  /** 设置多选框 */
  // const oversightMemo = useMemo(() => {
  //   let rowSelectInfo: Record<string, any> = {};
  //   rowSelectInfo = {
  //     rowSelection: {
  //       type: 'checkBox',
  //       getCheckboxProps: () => ({}),
  //       selectedRowKeys,
  //       onSelect: (record: any, selected: boolean) => {
  //         if (selected) {
  //           // 添加
  //           setSelectedRowKeys([...selectedRowKeys, record.id]);
  //           setSelectedRows([...selectedRows, record]);
  //         } else {
  //           // 去除
  //           const newSelectedRowKeys = selectedRowKeys.filter((key) => key !== record.id);
  //           const newSelectedRows = selectedRows.filter((row) => row.id !== record.id);
  //           setSelectedRowKeys(newSelectedRowKeys);
  //           setSelectedRows(newSelectedRows);
  //         }
  //       },
  //       onSelectAll: (selected: boolean, _, changeRows: any[]) => {
  //         const dataKeys = dataSourceTable?.map((item) => item.id) || [];
  //         if (selected) {
  //           // 全选
  //           const allKeys = Array.from(new Set([...dataKeys, ...selectedRowKeys]));
  //           const allRows = [...selectedRows, ...changeRows];
  //           setSelectedRowKeys(allKeys);
  //           setSelectedRows(allRows);
  //         } else {
  //           // 全不选
  //           const remainingKeys = selectedRowKeys.filter((key) => !dataKeys.includes(key));
  //           const remainingRows = selectedRows.filter((row) => !changeRows.some((item) => item.id === row.id));
  //           setSelectedRowKeys(remainingKeys);
  //           setSelectedRows(remainingRows);
  //         }
  //       },
  //     },
  //   };
  //   return rowSelectInfo;
  // }, [selectedRowKeys]);

  /** 折旧计算接口 */
  const { calculationRun, calculationLoading } = calculationService((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      MaterialManageViewRef?.current?.setSearch({
        depreciationDate: moment(otherParams?.depreciationDate),
      });
    }
  }, curRes);

  /** 管理页面头部操作集合 */
  const tableActionList: AssetListManageAPI.IHeaderActionType = useMemo(() => {
    return [
      {
        title: '折旧计算',
        visible: curRes?.['/assetDepreciationCalculation/depreciation'] || false,
        type: 'primary',
        loading: calculationLoading,
        onClick: () => {
          if (dataSourceTable?.length) {
            setIsShowDepreModal(true);
          } else {
            message?.warn('暂无需要折旧的资产，请重新选择折旧月份！');
          }

          // calculationRun({ depreciationDate: otherParams?.depreciationDate });
          // if (selectedRows?.length) {
          //   const list = selectedRows?.map((item) => item?.id);
          //   calculationRun({ assetListIds: list?.join(','), depreciationDate: otherParams?.depreciationDate });
          // } else {
          //   message?.warn('请选择资产进行折旧！');
          // }
        },
      },
      {
        title: '折旧记录',
        visible: true,
        type: 'primary',
        onClick: () => {
          setIsShowGatherModal(true);
        },
      },
    ];
  }, [curRes, selectedRowKeys, dataSourceTable, otherParams]);

  // useEffect(() => {
  //   if (history.location.pathname == '/AssetDepreciationCalculationController/manage') {
  //     reloadTableData();
  //   }
  // }, [history.location.pathname]);

  /** 设置默认搜索条件 */
  useEffect(() => {
    MaterialManageViewRef?.current?.setSearch({
      depreciationDate: moment()?.subtract(1, 'months'),
    });
  }, []);

  return (
    <>
      <div
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <SchemaManage
          ref={MaterialManageViewRef}
          searchProps={{
            switchList: [], //头部切换列表
            searchList,
            onSwitch,
            onReset,
            onSearch,
          }}
          actionList={tableActionList} // 操作按钮
          tableProps={{
            columns: columns,
            dataSource: dataSourceTable ? dataSourceTable : [],
            rowKey: 'id',
            loading: loading || childLoading || calculationLoading,
            pagination: pagination as any,
            onPageChange: onPageChange,
            expandable: {
              onExpand: onExpandTable,
              expandedRowKeys: tableExpantKeys,
            },
            // ...oversightMemo,
          }}
        />

        {isShowGatherModal && <GatherModal curRes={curRes} onCloseModal={() => setIsShowGatherModal(false)} />}

        {isShowDepreModal && (
          <TipsErrorModalNew
            modalLoading={calculationLoading}
            onClose={() => setIsShowDepreModal(false)}
            modalOnOK={() => calculationRun({ depreciationDate: otherParams?.depreciationDate })}
            modalTip={
              <>
                请确认是否进行<span>【{otherParams?.depreciationDate.slice(0, -3)}】</span>的折旧计算！
              </>
            }
          />
        )}
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(AssetListTableManageView);
